package distrcomp;

import java.io.File;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.rmi.ssl.SslRMIClientSocketFactory;

public class SubserverMain {
	public static void main(String[] args) throws RemoteException {
		SubserverImpl s;
		/*
		boolean restore = false;
		
		//Check if there is a back up file.
		File backup = new File("state.dat");
		if(backup.exists()) {
			s = new SubserverImpl(true);
			restore = true;
		} else {
			s = new SubserverImpl();
		}*/
		s = new SubserverImpl();
		
		//Set security manager
		try {
			SecurityManager sm = new SecurityManager();
		    System.setSecurityManager(sm);
		} catch(SecurityException e) {
			System.out.println("Could not set security manager.");
		}

		//Register the service with the registry running on another machine
		try {
			String regStr;
			if(args.length > 1) {
				regStr = args[1]; 
			} else {
				regStr = "localhost";
			}
			Registry registry = LocateRegistry.getRegistry(regStr, 1099, new SslRMIClientSocketFactory());
			RegisterSubserver reg = (RegisterSubserver) registry.lookup("RegisterService");
			//if(restore) {
			//	reg.register(s, s.getID());
			//} else {
				int ID = reg.register(s);
				s.setID(ID);
			//}
		} catch (NotBoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
